package com.wl.ribbonconsumer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author wangl
 * @desc
 * @date:2017/6/2011:43
 * @Copyright (c) 2017, DaChen All Rights Reserved.
 */
@Service
public class ComputeService {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @HystrixCommand(fallbackMethod = "addServiceFallback",
        commandProperties = {
            @HystrixProperty(name="execution.isolation.strategy", value="SEMAPHORE"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "50"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "100"),
            @HystrixProperty(name = "execution.isolation.semaphore.maxConcurrentRequests", value = "30")
        }
    )
    public String addService(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("compute-service");
        System.out.println("uri: "+serviceInstance.getUri());
        System.out.println(serviceInstance.getMetadata());
        String str = restTemplate.getForEntity("http://config-client/abc?a=10&b=20", String.class).getBody();
        System.out.println("config res : "+str);
        return restTemplate.getForEntity("http://compute-service/add?a=10&b=20", String.class).getBody();
    }

    private String addServiceFallback(){
        return "这个是失败的信息！";
    }
}
